package com.yang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yang.mapper.AttendanceRecordMapper;
import com.yang.mapper.LeaveMapper;
import com.yang.mapper.PerformanceRulesMapper;
import com.yang.mapper.TaskReplacementMapper;
import com.yang.pojo.AttendanceRecord;
import com.yang.pojo.Leave;
import com.yang.pojo.PerformanceRules;
import com.yang.pojo.TaskReplacement;
import com.yang.responseEntity.BaiDuApiEntity;
import com.yang.service.AttendanceRecordService;
import com.yang.util.JsonResult;
import com.yang.util.UrlUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @Author 杨天可
 * @Date 2021/3/15 10:17
 * @Version 1.0
 */
@Transactional
@RestController
@RequestMapping("/attendance")
public class AttendanceRecordController {

    @Resource
    PerformanceRulesMapper performanceRulesMapper;
    @Resource
    AttendanceRecordMapper attendanceRecordMapper;
    @Resource
    AttendanceRecordService attendanceRecordService;
    @Resource
    LeaveMapper leaveMapper;
    @Resource
    UrlUtil urlUtil;
    @Resource
    TaskReplacementMapper taskReplacementMapper;

    /***
     * 员工每天考勤（如果是上班打卡，endTime传空，如果下班打卡，beginTime传空）
     * @param userId  员工id
     * @param beginTime  员工上班打卡时间
     * @param endTime 员工下班打卡时间
     * @return 员工是否打卡成功
     */
    @GetMapping("/checkWork")
    public Map<String, Object> checkWork(@RequestParam("userId") Integer userId, @RequestParam("beginTime") String beginTime, @RequestParam("endTime") String endTime) throws ParseException {
        JsonResult jsonResult = new JsonResult();

        try {
            //获取当前位置
            JSONObject jsonObject = urlUtil.
                    sendUrlRequest("http://api.map.baidu.com/location/ip?ak=vFxhy9mf8Fm9EINUG1EiLO1qnTLoPhDo&ip=&coor=bd09ll");
            BaiDuApiEntity baiDuApiEntity = JSON.parseObject(jsonObject.toString(), BaiDuApiEntity.class);


            //获取公司位置
            JSONObject jsonObject1 = urlUtil.
                    sendUrlRequest("http://api.map.baidu.com/location/ip?ak=vFxhy9mf8Fm9EINUG1EiLO1qnTLoPhDo&ip=61.139.2.69&coor=bd09ll");
            BaiDuApiEntity baiDuApiEntity1 = JSON.parseObject(jsonObject1.toString(), BaiDuApiEntity.class);

            PerformanceRules theRules = performanceRulesMapper.findTheRules();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat todayDateFormat = new SimpleDateFormat("yyyy-MM-dd ");
            if (baiDuApiEntity.getContent().getPoint().getX().equals(baiDuApiEntity1.getContent().getPoint().getX())
                    && baiDuApiEntity.getContent().getPoint().getY().equals(baiDuApiEntity1.getContent().getPoint().getY())) {
                if ( !beginTime.trim().equals("") && endTime.trim().equals("")) {//上班打卡
            /*
            上班打卡时直接插入数据，等到下班打卡时再统计（是否迟到，是否旷工，是否请假，出勤天数）
             */
                    Date parse = simpleDateFormat.parse(beginTime);
                    AttendanceRecord attendanceRecord = new AttendanceRecord();
                    attendanceRecord.setUserId(userId);
                    attendanceRecord.setBeginTime(parse);
                    attendanceRecord.setWorkDate(todayDateFormat.parse(todayDateFormat.format(new Date())));
                    attendanceRecord.setInsertTime(new Date());
                    int insert = attendanceRecordMapper.insert(attendanceRecord);
                    if (insert > 0) {
                        jsonResult.setMsg("打卡成功");
                        jsonResult.setCode("200");
                    }
                } else {//下班打卡
                    AttendanceRecord attendanceByUserId = attendanceRecordMapper.getAttendanceByUserId(userId);
                    Leave recordByUserIdAndDate = leaveMapper.getRecordByUserIdAndDate(userId, todayDateFormat.parse(todayDateFormat.format(new Date())));
                    if (recordByUserIdAndDate == null) {//该员工今天未请假，按正常考勤规则
                        String beginWorkTime = todayDateFormat.format(new Date())+" "+theRules.getStartWorkTime();
                        String endWorkTime = todayDateFormat.format(new Date())+" "+theRules.getEndWorkTime();
                        boolean late = attendanceByUserId.getBeginTime().after(simpleDateFormat.parse(beginWorkTime));//true:上班迟到
                        boolean before = simpleDateFormat.parse(endTime).before(simpleDateFormat.parse(endWorkTime));//true: 下班早退

                        //统计该天出勤情况
                        if (late) {//上班迟到，
                            attendanceByUserId.setIsLate(1);
                        }
                        if (before) {//下班早退
                            attendanceByUserId.setIsBefore(1);
                        }
                        attendanceByUserId.setIsAbsent(0);
                        attendanceByUserId.setIsBefore(0);
                        attendanceByUserId.setIsLate(0);
                        attendanceByUserId.setEndTime(simpleDateFormat.parse(endTime));
                        attendanceByUserId.setIsLeave(0);

                    } else {
                        attendanceByUserId.setIsLeave(1);
                        attendanceByUserId.setIsLate(0);
                        attendanceByUserId.setIsBefore(0);
                    }

                    int i = attendanceRecordMapper.updateByPrimaryKey(attendanceByUserId);
                    if (i > 0) {
                        jsonResult.setMsg("打卡成功");
                        jsonResult.setCode("200");
                    }

                }
            } else {
                jsonResult.setMsg("超出打卡范围");
                jsonResult.setCode("200");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setCode("500");
            jsonResult.setMsg("系统开小差");
        }
        return jsonResult.getValues();
    }

    /***
     * 申请补卡（只能下班补卡，上班没有补卡）
     * @param workDate 需要补卡的日期
     * @param userInfoId 员工id
     * @return 申请是否成功
     */
    @GetMapping("/replacement")
    public Map<String,Object> replacement(@RequestParam("workDate")String workDate,@RequestParam("userInfoId")Integer userInfoId){
        JsonResult jsonResult = new JsonResult();
        try{
            SimpleDateFormat todayDateFormat = new SimpleDateFormat("yyyy-MM-dd ");
            //查找该员工当天打卡记录
            AttendanceRecord byWorkDateAndId = attendanceRecordService.
                    findByWorkDateAndId(todayDateFormat.parse(todayDateFormat.format(workDate)), userInfoId);
            if(byWorkDateAndId != null){
                TaskReplacement taskReplacement = new TaskReplacement();
                taskReplacement.setUserInfoId(userInfoId);
                taskReplacement.setWorkDate(todayDateFormat.parse(todayDateFormat.format(workDate)));

                int insert = taskReplacementMapper.insert(taskReplacement);
                if(insert > 0){
                    jsonResult.setCode("200");
                    jsonResult.setMsg("申请成功");
                }
            }else {
                jsonResult.setMsg("您当前没有打卡记录");
                jsonResult.setCode("200");
            }
        }catch(Exception e){
            e.printStackTrace();
            jsonResult.setMsg("系统开小差");
            jsonResult.setCode("500");
        }
        return jsonResult.getValues();
    }
}
